/*
 * Copyrignt (c) doubimeizhi.com. All Rights Reserved.
 * Author: mr.gao<fbg@live.com>
 * Created Time: 2016-12-07 15:06
 * Last Modified: 2017-07-28 14:36:11
 * File Name: qkcoupon/controllers/coupon_count.go
 * Description:
 */

package controllers

import (
	"qkcoupon/db"
	"qkcoupon/errorcode"
	"qkcoupon/rpc/client/passport"
	"qkcoupon/utils"

	log "github.com/cihub/seelog"
)

type CouponCountController struct {
	LoginedController
}

/*
 *@note  验证请求参数
 *@return (uint, string, int32, int32, string, int32): (错误码, uid, cstate, ctype, bid, version)
 */
func (p *CouponCountController) verification() (uint, string, int32, int32, string, int32) {
	var errCode uint = errorcode.EC_GL_SUCCESS
	var uid string = ""
	var cstate int32 = 0
	var ctype int32 = 0
	var bid string = ""
	var version int32 = 0

	for {
		var err error

		uid = p.GetString("uid", "")
		if uid == "" {
			log.Warn("uid == ''")
			errCode = errorcode.EC_GL_INVALID_URL_PARAMS
			break
		}

		cstate, err = p.GetInt32("cstate", 0)
		if err == nil && cstate != 0 {
			if !utils.CheckCState(cstate) {
				log.Warn("EQKCOUPON_STATE_name[cstate] not exist")
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}
		}

		ctype, err = p.GetInt32("ctype", 0)
		if err == nil && ctype != 0 {
			if !utils.CheckCType(ctype) {
				log.Warn("EQKCOUPON_TYPE_name[ctype] not exist")
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}
		}

		bid = p.GetString("bid", "")

		version, _ = p.GetInt32("version", 0)

		break
	}

	return errCode, uid, cstate, ctype, bid, version
}

// @router /count [get]
func (p *CouponCountController) CouponCount() {
	defer p.Output("CouponCount")

	errCode, uid, cstate, ctype, bid, version := p.verification()
	if errCode != errorcode.EC_GL_SUCCESS {
		p.Resp["code"] = errCode
		return
	}

	up, errCode := passport.GetUserProfileByUID(uid)
	if errCode != errorcode.EC_GL_SUCCESS || up.Mobile == "" {
		p.Resp["code"] = errCode
		return
	}

	cc, errCode := db.GetCouponCount(uid, up.Mobile, cstate, ctype, bid, version)

	p.Resp["code"] = errCode

	if errCode == errorcode.EC_GL_SUCCESS {
		p.Resp["data"] = cc
	}
}
